package servlet;

import user.Member;
import util.DBUtilDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

//准备支付
public class MyOrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        float money = Float.parseFloat(request.getParameter("money"));//所支付的金额
        String phoneNumber = (String) request.getSession().getAttribute("username");
        Member member = null;
        DBUtilDao dbUtilDao = new DBUtilDao();
        try {
            member = dbUtilDao.getMember(phoneNumber); //查询数据表member2当前用户的余额和积分
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (member.getBalance() >= money) {//余额充足，可以支付订单
            try {
                dbUtilDao.updateOrder(phoneNumber, 1); //改变订单为已支付状态
                request.getSession().removeAttribute("orderCar"); //清空未完成的订单
                dbUtilDao.updateMember(new Member(phoneNumber, member.getIntegral(), member.getBalance() - money, member.getCoupon()));//更新积分，余额，优惠券


                Member member1 = dbUtilDao.getMember(phoneNumber);
                request.getSession().setAttribute("member", member1);//更新session域的用户余额
                request.getSession().removeAttribute("order");
                SelectOrderCarServlet selectOrderCarServlet = new SelectOrderCarServlet();
                selectOrderCarServlet.doGet(request, response); //刷新订单信息

                SelectShopCarServlet selectShopCarServlet = new SelectShopCarServlet();
                selectShopCarServlet.doGet(request, response); //刷新购物车信息

                response.sendRedirect("myordered.jsp"); //重定向到已完成的界面
                try {
                    dbUtilDao.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }


        } else {//钱不够
            try {
                dbUtilDao.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            response.getWriter().println("余额不足，请充值后再支付！！！（2秒后自动跳转）");
            response.setHeader("refresh", "2;URL=money.jsp");

        }
    }
}
